<template>
  <div>
<el-upload
  class="upload-demo"
  action="http://192.168.124.23:3000/load"
  :headers="tokenheader"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :file-list="fileList"
  :on-error="uploaderror"
  list-type="picture">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
</el-upload>
  </div>
</template>

<script>
import { mapState } from "vuex";
import jwt from "jsonwebtoken";
export default {
  data() {
    return {
      fileList:[]
    };
  },
  methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      uploaderror(err,file,filelist){
        console.log(err);
        console.log(file);
      },
      uploadok(res,file,filelist){
        console.log(res);
        console.log(file);
      }
    },
  computed: {
    tokenheader(){
       console.log(this.token);
       return {Authorization:this.token};
    },
    ...mapState("app", ["appname", "username", "userid", "powercode", "token"])
  },
  beforeRouteEnter(to, from, next) {
    //检查token 是否存在 ，然后到服务器端验证是否正确
    next(vm => {
      console.log(vm.$store.state.app);
      if (vm.token && vm.token.length > 10) {
        console.log(vm.token);
        let service = vm.axios.create({
          baseURL: "http://192.168.124.23:3000",
          timeout: 2000
        });
        service.interceptors.request.use(config => {
          //const token = jwt.sign({ name: "Tokken" }, "sec");
          config.headers.common["Authorization"] =  vm.token;
          return config;
        });
        let url = "/checktoken";
        service({
          url,
          method: "get"
        })
          .then((res, err) => {
            if (err) {
              console.log("-----------error------------");
              console.log(err);
              vm.$router.push({ path: "/" });
            } else {
              console.log(res);
            }
          })
          .catch(err => {
            console.log(err);
            vm.$router.push({ path: "/" });
          });
      } else {
        vm.$router.push({ path: "/" });
      }
    });
  }
};
</script>